package com.cancer.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class WeixinUtil {
    /**
     * token放入内存中
     */
    public static Map<String,Object> currentToken = new ConcurrentHashMap<String,Object>();
    /**
     * jsapi_ticket放入内存中
     */
    public static Map<String,Object> jsapiTicket= new ConcurrentHashMap<String,Object>();
    public static String STR_UTF8 = "utf-8";
    
 // 各种消息类型,除了扫带二维码事件
    /**
     * 文本消息
     */
    public static final String MESSAGE_TEXT = "text";
    /**
     * 图片消息
     */
    public static final String MESSAtGE_IMAGE = "image";
    /**
     * 图文消息
     */
    public static final String MESSAGE_NEWS = "news";
    /**
     * 语音消息
     */
    public static final String MESSAGE_VOICE = "voice";
    /**
     * 视频消息
     */
    public static final String MESSAGE_VIDEO = "video";
    /**
     * 小视频消息
     */
    public static final String MESSAGE_SHORTVIDEO = "shortvideo";
    /**
     * 地理位置消息
     */
    public static final String MESSAGE_LOCATION = "location";
    /**
     * 链接消息
     */
    public static final String MESSAGE_LINK = "link";
    /**
     * 事件推送消息
     */
    public static final String MESSAGE_EVENT = "event";
    /**
     * 事件推送消息中,事件类型，subscribe(订阅)
     */
    public static final String MESSAGE_EVENT_SUBSCRIBE = "subscribe";
    /**
     * 事件推送消息中,事件类型，unsubscribe(取消订阅)
     */
    public static final String MESSAGE_EVENT_UNSUBSCRIBE = "unsubscribe";
    /**
     * 事件推送消息中,上报地理位置事件
     */
    public static final String MESSAGE_EVENT_LOCATION_UP = "LOCATION";
    /**
     * 事件推送消息中,自定义菜单事件,点击菜单拉取消息时的事件推送
     */
    public static final String MESSAGE_EVENT_CLICK = "CLICK";
    /**
     * 事件推送消息中,自定义菜单事件,点击菜单跳转链接时的事件推送
     */
    public static final String MESSAGE_EVENT_VIEW = "VIEW";
	public static boolean checkSignature(String signature, String timestamp,
	          String nonce,String token) {
	      //从请求中（也就是微信服务器传过来的）拿到的token, timestamp, nonce
	      String[] arr = new String[] { token, timestamp, nonce };
	      // 将token、timestamp、nonce三个参数进行字典序排序
	      sort(arr);
	      StringBuilder content = new StringBuilder();
	      for (int i = 0; i < arr.length; i++) {
	          content.append(arr[i]);
	      }
	      MessageDigest md = null;
	      String tmpStr = null;
	
	      try {
	          md = MessageDigest.getInstance("SHA-1");
	          // 将三个参数字符串拼接成一个字符串进行sha1加密
	          byte[] digest = md.digest(content.toString().getBytes());
	          //将字节数组转成字符串
	          tmpStr = byteToStr(digest);
	      } catch (NoSuchAlgorithmException e) {
	          e.printStackTrace();
	      }
	
	      content = null;
	      // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
	      return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	    }
	//将加密后的字节数组变成字符串
   private static String byteToStr(byte[] byteArray) {
       String strDigest = "";
       for (int i = 0; i < byteArray.length; i++) {
           strDigest += byteToHexStr(byteArray[i]);
       }
       return strDigest;
   }

   private static String byteToHexStr(byte mByte) {
       char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
               'B', 'C', 'D', 'E', 'F' };
       char[] tempArr = new char[2];
       tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
       tempArr[1] = Digit[mByte & 0X0F];

       String s = new String(tempArr);
       return s;
   }
	//用于字典排序
	public static void sort(String a[]) {
	     for (int i = 0; i < a.length - 1; i++) {
	         for (int j = i + 1; j < a.length; j++) {
	             if (a[j].compareTo(a[i]) < 0) {
	                 String temp = a[i];
	                 a[i] = a[j];
	                 a[j] = temp;
	             }
	         }
	     }
	  }
	/**
     * 将xml转化为Map集合
     * 
     * @param request
     * @return
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        try {
            ins.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return map;
    }

      public static String getCurrentToken() {
          return currentToken.get("currentToken").toString();
      }
      public static void setCurrentToken(java.util.Map<String, Object> currentToken) {
          WeixinUtil.currentToken = currentToken;
      }
    public static String getJsapiTicket() {
        return jsapiTicket.get("currentJsTicket").toString();
    }
    public static void setJsapiTicket(Map<String, Object> jsapiTicket) {
        WeixinUtil.jsapiTicket = jsapiTicket;
    }
    
}
